package net;

import com.msg.MsgMain;
import game.Client;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import net.message.MsgNotWritableCacheManager;
import net.message.MsgPack;
import util.LogUtil;

public class NettyProtobufClientHandler extends SimpleChannelInboundHandler<MsgMain.MainProtocl> {

    private Client client;

    public NettyProtobufClientHandler(Client client) {
        super();
        this.client = client;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, MsgMain.MainProtocl mainProtocl) throws Exception {
        final int msgIndex = mainProtocl.getMessageType().getNumber();
        Channel channel = channelHandlerContext.channel();
        MsgPack msg = new MsgPack(msgIndex, mainProtocl, channel, this.client);
        this.client.addMessagePack(msg);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        this.client.onChannelActive(ctx.channel());
        MsgNotWritableCacheManager.getInstance().clear(ctx.channel());
        /**
         * 作用：触发事件告知Inbound ChannelHandler：
         * ChannelHandlerContext的Channel现在处于活动状态，
         * 调用ChannelInboundHandler的channelActive
         */
        ctx.fireChannelActive();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        MsgNotWritableCacheManager.getInstance().clear(ctx.channel());
        ctx.close();
        LogUtil.game.warn("链接异常:" + cause);
    }

    @Override
    public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
        super.channelWritabilityChanged(ctx);
        //尝试重新发送被isWritable = false拒绝的消息
        MsgNotWritableCacheManager.getInstance().trySendMsgAgain(ctx.channel());
    }
}
